package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import artid.com.arttogoa.R;

import artid.com.arttogoa.barcode.Bimp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.glide.GlideUtil;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.parser.MySellInfoParser;
import artid.com.arttogoa.parser.MySellInfo_ImageBean;
import artid.com.arttogoa.parser.RecordDetailList;
import artid.com.arttogoa.photo.ImagePagerActivity;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.UploadTheSaleOfGoodsUtils;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称 ：EditFilingQuickSell_Activity 类描述 ：编辑备案一键出售 创建人 ：耿卫斌
 * 创建时间：2016-7-14 上午10:20:48
 * 
 * 
 * 跳转地址： EditSize_Activity.class ：编辑尺寸页面 MySell_Activity.class : 我出售的
 * 
 */
public class EditFilingQuickSell_Activity extends BaseActivity implements
		OnClickListener {
	private Context mContext;
	private TextView subMitBtn;
	private String art_id = "";// 备案列表传过来的ID
	private MySellInfoParser mMySellInfoParser;// 我的出售详情编辑数据
	/** 来源（发布or编辑） */
	private int goodsType;
	private TextView author/** 作者 */
	, name/** 名称 */
	, goodssize/** 尺寸 */
	, goodsage/** 年代 */
	, goodstype/** 类别 */
	, certificateNumber/** 证书编号 */
	;
	private EditText price/** 价格 */
	, introduce/** 商品简介 */
	;
	private TextView electronicFF/** 电子证书 */
	, paperFF/** 纸质证书 */
	;
	/**
	 * 是否是纸质证书
	 */
	private boolean FFtype = true;
	/**
	 * 九宫格展示图片
	 */
	private GridView mGridView;
	private GridAdapter adapter;
	/**
	 * 编辑所需
	 */
	private List<String> deleteIds = new ArrayList<String>();;// 需要删除的图片的id
	public List<FilesBean> imageArr = new ArrayList<FilesBean>();// 新增的图片

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_editfilingquicksell);
		setContent(this, getIntent());
		mContext = EditFilingQuickSell_Activity.this;
		Bimp.drr.clear();
		initView();
	}

	private void initView() {
		mTittle.setText("备案一键出售");
		mBack.setOnClickListener(this);
		mMySellInfoParser = new MySellInfoParser();
		subMitBtn = (TextView) findViewById(R.id.edit_sellinfo_submit);
		subMitBtn.setOnClickListener(this);
		
		author = (TextView) findViewById(R.id.tv_sellinfo_author);// 作者
		name = (TextView) findViewById(R.id.tv_sellinfo_goodsname);// 名称

		introduce = (EditText) findViewById(R.id.edit_sellinfo_goodsintroduce);// 简介
		price = (EditText) findViewById(R.id.edit_sellinfo_goodsprice);// 价格
		price.addTextChangedListener(mPriceListener);
		price.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
		goodssize = (TextView) findViewById(R.id.edit_sellinfo_goodssize);
		goodsage = (TextView) findViewById(R.id.edit_sellinfo_goodsage);
		goodstype = (TextView) findViewById(R.id.edit_sellinfo_goodstype);
		certificateNumber = (TextView) findViewById(R.id.tv_sellinfo_Certificatenumber);
		
		paperFF = (TextView) findViewById(R.id.edit_sellinfo_filingcertificate_paper);// 纸质证书
		electronicFF = (TextView) findViewById(R.id.edit_sellinfo_filingcertificate_electronic);// 电子证书
		paperFF.setOnClickListener(this);
		electronicFF.setOnClickListener(this);
		
		mGridView = (GridView) findViewById(R.id.grid);
		// filesList = new ArrayList<FilesBean>();
		adapter = new GridAdapter(mContext);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.drr.size()) {
					Intent in = new Intent(mContext, LocalAlbumActivity.class);
					startActivity(in);
				} else {
					imageBrower(arg2);
				}
			}
		});
		
		goodsType = getIntent().getIntExtra("goodsType", 0);
		if (goodsType == Bimp.GOODS_EDIT) {
			// 获取我的出售详情编辑数据
			mMySellInfoParser = (MySellInfoParser) getIntent()
					.getSerializableExtra("MySellInfoParser");
			author.setText(AppUtil.getUser().getRealname());
			name.setText(mMySellInfoParser.getGoods_name());
			goodssize.setText(mMySellInfoParser.getSpec_value() + "");
			goodsage.setText(mMySellInfoParser.getGoods_age() + "");
			goodstype.setText(mMySellInfoParser.getGc_name() + "");
			introduce.setText(mMySellInfoParser.getDetail() + "");
			String priceValue = mMySellInfoParser.getGoods_price();
			try {
				price.setText(priceValue.contains(".") ? priceValue.substring(
						0, priceValue.indexOf('.')) + "" : priceValue);
			} catch (Exception e) {
				// TODO: handle exception
				price.setText("价格截取错误!!!");
			}
			certificateNumber.setText(mMySellInfoParser.getCode() + " ");
			if (mMySellInfoParser.getBy_state().equals("2")) {
				FFtype = true;
			} else {
				FFtype = false;
			}
			setFFtype();
			List<MySellInfo_ImageBean> goods_image = mMySellInfoParser
					.getGoods_image();
			for (int i = 0; i < goods_image.size(); i++) {
				FilesBean fb = new FilesBean();
				fb.setImgURL(goods_image.get(i).getGoods_image());
				fb.setImgId(goods_image.get(i).getGoods_image_id());
				fb.setSelected(false);
				Bimp.drr.add(fb);
			}
		} else {
			art_id = getIntent().getStringExtra("art_id");
			reqAtristListData();
		}
	}

	/**
	 * 打开图片查看器
	 * 
	 * @param position
	 * @param urls2
	 */
	protected void imageBrower(int position) {
		ArrayList<String> urls2 = new ArrayList<String>();
		for (int i = 0; i < Bimp.drr.size(); i++) {
			urls2.add(Bimp.drr.get(i).getImgURL());
		}
		Intent intent = new Intent(mContext, ImagePagerActivity.class);
		// 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
		intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_TYPE,
				ImagePagerActivity.LATTICE);
		mContext.startActivity(intent);
	}

	RecordDetailList item;

	/**
	 * 
	 * @Title: reqAtristListData
	 * @Description: TODO(请求备案详情)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void reqAtristListData() {
		VolleyBasic.getInstance(EditFilingQuickSell_Activity.this).post(
				Cache.recorddetaillist,
				VolleyMap.getInstance().recorddetaillist(art_id),
				RecordDetailList.class, new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						item = (RecordDetailList) vd.getData();
						System.out.println(item.toString());
						ArrayList<RecordDetailList.Pointinformation> list = item
								.getPointinformation();
						// ArrayList<Pointinformation> list1 = new
						// ArrayList<RecordDetailList.Pointinformation>();
						for (int i = 0; i < 2; i++) {
							FilesBean f = new FilesBean();
							f.setImgURL(list.get(i).getImgurl());
							f.setDeleteStatus(true);
							Bimp.drr.add(f);
						}
						adapter.notifyDataSetChanged();
						author.setText(item.getRealname());
						name.setText(item.getTitle());
						goodsage.setText(item.getAge());
						goodssize.setText(item.getWidth() + " x "
								+ item.getHeight());
						goodstype.setText(item.getArt_type());
						certificateNumber.setText(item.getCode() + " ");
					}

					@Override
					public void onError(VolleyError volleyError) {

					}
				});

	}

	public void setFFtype() {
		if (FFtype) {
			Drawable img_on, img_off;
			Resources res = getResources();
			img_off = res.getDrawable(R.drawable.paiz_information_select_nor);
			img_on = res.getDrawable(R.drawable.paiz_information_select_sel2);
			// 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
			img_off.setBounds(0, 0, img_off.getMinimumWidth(),
					img_off.getMinimumHeight());
			img_on.setBounds(0, 0, img_off.getMinimumWidth(),
					img_off.getMinimumHeight());
			electronicFF.setCompoundDrawables(img_on, null, null, null); // 设置左图标
			paperFF.setCompoundDrawables(img_off, null, null, null); // 设置左图标
			FFtype = false;
		} else {
			Drawable img_on, img_off;
			Resources res = getResources();
			img_off = res.getDrawable(R.drawable.paiz_information_select_nor);
			img_on = res.getDrawable(R.drawable.paiz_information_select_sel2);
			// 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
			img_off.setBounds(0, 0, img_off.getMinimumWidth(),
					img_off.getMinimumHeight());
			img_on.setBounds(0, 0, img_off.getMinimumWidth(),
					img_off.getMinimumHeight());
			paperFF.setCompoundDrawables(img_on, null, null, null); // 设置左图标
			electronicFF.setCompoundDrawables(img_off, null, null, null); // 设置左图标
			FFtype = true;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.edit_sellinfo_filingcertificate_paper:// 纸质证书
			setFFtype();
			break;
		case R.id.edit_sellinfo_filingcertificate_electronic:// 电子证书
			setFFtype();
			break;
		case R.id.back_btn:
			if (goodsType == Bimp.GOODS_PUBLISH) {
				finish();
			} else {// zheshiyige
				AlertUtils.AlertTwoBtnDialog(mContext,
						"您变更的作品信息还未提交，\n确定离开此页面？", "确定", "取消",
						getWindowManager().getDefaultDisplay().getWidth(),
						backClick);
			}
			break;
		case R.id.edit_sellinfo_submit:
			// 确定出售
			if (goodsType == Bimp.GOODS_PUBLISH) {
				submit();
			} else {
				AlertUtils.AlertTwoBtnDialog(mContext, "确定提交变更的作品信息？", "确定",
						"取消",
						getWindowManager().getDefaultDisplay().getWidth(),
						submitClick);
			}
			break;

		default:
			break;
		}
	}

	OnClickListener submitClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_ok:
				AlertUtils.dismiss();
				submit();
				break;
			case R.id.tv_no:
				AlertUtils.dismiss();
				break;

			default:
				break;
			}
		}
	};
	OnClickListener backClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_ok:
				AlertUtils.dismiss();
				finish();
				break;
			case R.id.tv_no:
				AlertUtils.dismiss();
				break;

			default:
				break;
			}
		}
	};
	
	/**
	 * 对价格输入的监听
	 */
	TextWatcher mPriceListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			if(!StringUtils.isEmpty(price.getText().toString())){
				if(Integer.parseInt(price.getText().toString())==0){
					price.setText("");
					showToast("价格不能以0开头,请重新填写");
				}
			}
		}  
	};  

	/**
	 * 
	 * @Title: submit
	 * @Description: TODO 发布商品
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void submit() {
		// TODO Auto-generated method stub
		// String authorText = author.getText().toString().trim();
		String introduceText = introduce.getText().toString().trim();
		String priceText = price.getText().toString().trim();
		if (TextUtils.isEmpty(introduceText)) {
			Toast.makeText(mContext, "商品简介不能为空~", Toast.LENGTH_LONG).show();
			return;
		} else if (TextUtils.isEmpty(priceText)) {
			Toast.makeText(mContext, "价格不能为空~", Toast.LENGTH_LONG).show();
			return;
		}
		mMySellInfoParser.setGoods_name(name.getText().toString().trim());// 名称
		mMySellInfoParser.setSpec_value(goodssize.getText().toString().trim());
		mMySellInfoParser.setGc_name("4");
		mMySellInfoParser.setGoods_age("4");
		mMySellInfoParser.setDetail(introduceText);
		mMySellInfoParser.setGoods_price(priceText);
		mMySellInfoParser.setIs_auth("1");
		mMySellInfoParser.setBy_state(FFtype ? "2" : "1");
		mMySellInfoParser.setGoods_image1(Bimp.drr.get(0).getImgURL());
		mMySellInfoParser.setGoods_image2(Bimp.drr.get(1).getImgURL());
		List<MySellInfo_ImageBean> sibList = new ArrayList<MySellInfo_ImageBean>();

		for (int i = 2; i < Bimp.drr.size(); i++) {
			if (Bimp.drr.get(i).isSelected()) {// 判断是否为新增，只有进入页面时有跟进对象时（编辑），才会有该值为false的情况
				MySellInfo_ImageBean mi = new MySellInfo_ImageBean(Bimp.drr
						.get(i).getImgURL());
				BitmapFactory.Options options = new BitmapFactory.Options();
				/**
				 * 最关键在此，把options.inJustDecodeBounds = true;
				 * 这里再decodeFile()，返回的bitmap为空
				 * ，但此时调用options.outHeight时，已经包含了图片的高了
				 */
				options.inJustDecodeBounds = true;
				Bitmap bitmap = BitmapFactory.decodeFile(Bimp.drr.get(i)
						.getImgURL(), options); // 此时返回的bitmap为null
				mi.setImage_height(options.outHeight);
				mi.setImage_width(options.outWidth);
				sibList.add(mi);
			}
		}
		mMySellInfoParser.setGoods_image(sibList);
		if (goodsType == Bimp.GOODS_EDIT) {
			mMySellInfoParser.setDelete_image_ids(deleteIds);// 需要删除的图片id
		}
		UploadTheSaleOfGoodsUtils ug = new UploadTheSaleOfGoodsUtils(
				EditFilingQuickSell_Activity.this, mMySellInfoParser, goodsType);
		ug.Upload();
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		// public void update() {
		// loading();
		// }

		public int getCount() {
			return (Bimp.drr.size() + 1) < 9 ? (Bimp.drr.size() + 1) : 9;
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_grid_main, parent,
						false);
				holder = new ViewHolder();
				holder.main = (TextView) convertView
						.findViewById(R.id.tv_main_img);
				holder.image = (ImageView) convertView.findViewById(R.id.icon);
				holder.delete = (ImageView) convertView
						.findViewById(R.id.iv_delete);
				holder.xuanze = (ImageView) convertView
						.findViewById(R.id.xuanze);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.drr.size()) {
				holder.main.setVisibility(View.GONE);
				holder.xuanze.setVisibility(View.VISIBLE);
				holder.image.setVisibility(View.GONE);
				if (position == 9) {
					holder.xuanze.setVisibility(View.GONE);
				}
			} else {
				if (coord == 0) {
					holder.main.setVisibility(View.VISIBLE);
				} else {
					holder.main.setVisibility(View.GONE);
				}
				holder.image.setVisibility(View.VISIBLE);
				holder.xuanze.setVisibility(View.GONE);

				/*
				 * final ImageView v = holder.image;
				 * Glide.with(mContext).load(Bimp.drr.get(coord).getImgURL())
				 * .asBitmap().into(new SimpleTarget<Bitmap>() {
				 * 
				 * @Override public void onResourceReady(Bitmap arg0,
				 * GlideAnimation<? super Bitmap> arg1) { // TODO Auto-generated
				 * method stub v.setImageBitmap(arg0);
				 * 
				 * } });
				 */

				GlideUtil.setImage(mContext, Bimp.drr.get(coord).getImgURL(),
						R.drawable.yspba_img_mor, R.drawable.yspba_img_mor,
						holder.image);
			}
			if (holder.xuanze.getVisibility() == View.VISIBLE) {
				holder.delete.setVisibility(View.GONE);
			} else {
				if (Bimp.drr.get(coord).isDeleteStatus()) {
					holder.delete.setVisibility(View.GONE);
				} else {
					holder.delete.setVisibility(View.VISIBLE);
				}
			}
			holder.delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					if (goodsType == Bimp.GOODS_EDIT
							&& !Bimp.drr.get(coord).isSelected()) {
						deleteIds.add(Bimp.drr.get(coord).getImgId());
					}
					Bimp.drr.remove(coord);
					notifyDataSetChanged();
				}
			});
			return convertView;
		}

		public class ViewHolder {
			public ImageView image, xuanze, delete;
			public TextView main;
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		adapter.notifyDataSetChanged();
	}
}
